from flask import Blueprint, views, render_template, url_for, redirect, session
from exts import db, mail
from flask_mail import Message
from .forms import LoginForm, ModifyPwdForm, ResetMailForm, MailCaptchaForm
from .models import CMSUser, CMSPermission
from .decorators import login_required, permission_required
from config import CMS_USER_ID
from utils import restful, cache, captcha

blueprint = Blueprint("cms", __name__, url_prefix="/cms")

# 后台管理系统首页
@blueprint.route("/")
@login_required
def index():
    return render_template("cms/cms_index.html")

# 登录视图
class LoginView(views.MethodView):
    def __init__(self):
        self.form = LoginForm()
    # 处理get请求
    def get(self):
        return self._render()

    # 处理post请求
    def post(self):
        form = self.form
        if form.validate_on_submit():
            email = form.email.data
            password = form.password.data
            user = CMSUser.query.filter_by(email=email).first()
            remember = form.remember.data
            # 判断用户是否存在且密码是否正确
            if user and user.check_password(password):
                session[CMS_USER_ID] = user.id
                if remember:
                    session.permanent = True

                return redirect(url_for("cms.index"))
            else:
                message = {"error": "邮箱或密码错误！"}
                return self._render(message)
        else:
            message = form.errors
            return self._render(message=message)

    def _render(self,message=None):
        return render_template("cms/login.html", form=self.form, message=message)



# 退出登录
@blueprint.route("/logout")
@login_required
def logout():
    session.clear()
    return redirect(url_for("cms.login"))

# 个人中心
@blueprint.route("/profile")
@login_required
def profile():
    return render_template("cms/cms_profile.html")

# 修改密码
class ModifyPwdView(views.MethodView):
    @login_required
    def get(self):
        return render_template("cms/cms_modifyPwd.html")
    def post(self):
        form = ModifyPwdForm()
        if form.validate_on_submit():
            oldPassword = form.oldPassword.data
            newPassword = form.newPassword.data
            id = session.get(CMS_USER_ID)
            user = CMSUser.query.filter_by(id=id).first()

            # 判断密码是否正确
            if user and user.check_password(oldPassword):
                user.updatePassword(newPassword)
                db.session.add(user)
                db.session.commit()

                return restful.success()
            else:
                return restful.params_error("旧密码不正确！")
        else:
            error = form.getError()
            return restful.params_error(error)

# 修改邮箱视图
class ResetMailView(views.MethodView):
    def get(self):
        return render_template("cms/cms_resetMail.html")
    def post(self):
        form = ResetMailForm()
        if form.validate_on_submit():
            email = form.email.data
            code = form.captcha.data
            # 获取验证码
            captcha_stored = cache.get(email)
            id = session.get(CMS_USER_ID)

            # 验证验证码是否正确
            user = CMSUser.query.filter_by(id=id).first()
            if code != captcha_stored:
                return restful.params_error("验证码错误！")
            else:
                # 删除验证码
                cache.delete(email)
                user.email = email
                db.session.add(user)
                db.session.commit()
                return restful.success()
        else:
            return restful.params_error(form.getError())

# 发送验证码
@blueprint.route("/sendMail", methods=["POST"])
def sendMail():
    form = MailCaptchaForm()
    if form.validate_on_submit():
        email = form.email.data
        code = captcha.get()
        # 将验证码存放在memcached中
        cache.set(email, code)
        # 发送邮件
        message = Message("验证码",
                          sender="liuwenchao1990@163.com",
                          recipients=[email],
                          body="验证码: {0}".format(code)
                          )
        mail.send(message=message)
        return restful.success()
    else:
        return restful.params_error(form.getError())


# 帖子管理
@blueprint.route("/post")
@login_required
@permission_required(CMSPermission.POSTER)
def post():
    return render_template("cms/cms_post.html")

# 评论管理
@blueprint.route("/comment")
@login_required
@permission_required(CMSPermission.COMMENTER)
def comment():
    return render_template("cms/cms_comment.html")

# 板块管理
@blueprint.route("/board")
@login_required
@permission_required(CMSPermission.BOARDER)
def board():
    return render_template("cms/cms_board.html")

# 用户管理
@blueprint.route("/fuser")
@login_required
@permission_required(CMSPermission.FRONTUSER)
def fuser():
    return render_template("cms/cms_fuser.html")

# cms用户管理
@blueprint.route("/cuser")
@login_required
@permission_required(CMSPermission.CMSUSER)
def cuser():
    return render_template("cms/cms_cuser.html")

# csm组管理
@blueprint.route("/role")
@login_required
@permission_required(CMSPermission.ADMINDER)
def role():
    return render_template("cms/cms_role.html")

# 定义路由
blueprint.add_url_rule("/modifyPwd", view_func=ModifyPwdView.as_view("modifyPwd"))
blueprint.add_url_rule("/login", view_func=LoginView.as_view("login"))
blueprint.add_url_rule("/resetMail", view_func=ResetMailView.as_view("resetMail"))


